/* import {
    constantRoutes
  } from '../../router'
  import Layout from '@/layout' */
import {
  routerViewConfig,
  resourceApiAliasConfig,
  resourcePermsKeyDefinedRule,
  hackSuffixJumpStr,
  getJumpTargetVal,
  getJumpTargetReourcePermsKey,
  realPageFilePathKeyFuc,
  getRealPageFileKey,
  getResourcePermsKeyInfo,
  generatePartialRealPageFileKeyStrategy,
  judgeIndividualPageRule,
  getCurResourceLastCode,
  getCompleteUrl,
  globalConfig,
} from "@gd-accbuild-core/config";

const Layout = routerViewConfig.Layout;
const middleLayout = Layout.middleLayout;
//import middleLayout from '@/views/default-page/middle-layout.vue'
import {
  isSuccessReqBackend,
  cloneDeep,
  transName,
  getBackendDataItems
} from "@gd-accbuild-core/config/utils";
const {
  resourceUrlKeyAlias,
  childrenKeyAlias,
  realPageFileKeyAlias,
  resourceTypeKeyAlias,
  resourcePermsKeyAlias,
  resourceNameAlias,
  resourceIconAlias,
  idKeyAlias,
  pidKeyAlias,
  targetKeyAlias,
  hasChildrenAlias,
  ordinalKeyAlias,
  uiOptionsKeyAlias,
} = resourceApiAliasConfig;

const allBuildInBtnInfoKeys = Object.keys(
  resourcePermsKeyDefinedRule.buildInBtnInfo
);

// TODO: key最好不要改变,会与mapMenuPageToRealPageUrl结合使用;且key默认与menuPage相同;
// menuPage 表示源码文件夹结构,一般不变
const mapKeyToView = {
  // 房产管理
  /* 'biz/region': {
      [realPageFileKeyAlias]: 'biz/region',
      view: () => Promise.resolve(require(`@/views/${this.componentFilePath}/index.vue`))
    } */
  // 'Index.vue':undefined
};

// 映射key到真实页面链接
//const mapKeyToRealPageUrl = {};
//const mapKeyToNavBreadcrumbTitle = {};

export class GVariable {
  constructor(StoragePrefix) {
    this.StoragePrefix = StoragePrefix;
    this.mapKeyToRealPageUrl = {};
    this.mapKeyToNavBreadcrumbTitle = {};
  }
}
const gVariable = new GVariable("store/permission/");
export const getState = (gVariable) => {
  return {
    routes: [],
    buttons: [],
    mapKeyToRealPageUrl: gVariable.mapKeyToRealPageUrl,
    mapKeyToNavBreadcrumbTitle: gVariable.mapKeyToNavBreadcrumbTitle,
    /* javascript-obfuscator:disable */
    pages: !!uni.getStorageSync(`${gVariable.StoragePrefix}pages`)
      ? JSON.parse(uni.getStorageSync(`${gVariable.StoragePrefix}pages`))
      : [],
    navTreeData: !!uni.getStorageSync(`${gVariable.StoragePrefix}navTreeData`)
      ? JSON.parse(uni.getStorageSync(`${gVariable.StoragePrefix}navTreeData`))
      : [],
    curPageInfo: !!uni.getStorageSync(`${gVariable.StoragePrefix}curPageInfo`)
      ? JSON.parse(uni.getStorageSync(`${gVariable.StoragePrefix}curPageInfo`))
      : { vmCode: "", treeVmCode: "", name: "" }, //当前访问的页面相关配置信息
    resourceTypeOptions: !!uni.getStorageSync(
      `${gVariable.StoragePrefix}resourceTypeOptions`
    )
      ? JSON.parse(
        uni.getStorageSync(`${gVariable.StoragePrefix}resourceTypeOptions`)
        )
      : [
          {
            disabled: false,
            group: null,
            selected: false,
            label: "菜单",
            value: "Menu",
          },
          {
            disabled: false,
            group: null,
            selected: false,
            label: "页面",
            value: "Page",
          },
          {
            disabled: false,
            group: null,
            selected: false,
            label: "按钮",
            value: "Button",
          },
          {
            disabled: false,
            group: null,
            selected: false,
            label: "接口",
            value: "Interface",
          },
        ], //资源类型选项
    /* javascript-obfuscator:enable */
  };
};
const state = getState(gVariable);
export const getGetters = (gVariable) => {
  return {
    resourceTypeMapping: (state) => {
      let obj = {};
      state.resourceTypeOptions.forEach((el) => {
        obj[el.value] = el.label;
      });
      return obj;
    },
    resourceTypeEnum: (state) => {
      let obj = {};
      state.resourceTypeOptions.forEach((el) => {
        obj[el.label] = el.value;
      });
      return obj;
    },
    routes: (state) => {
      return state.routes;
    },
  };
};
const getters = getGetters(gVariable);
export const getMutations = (gVariable) => {
  return {
    SET_ROUTES: (state, routes) => {
      const constantRoutes = globalConfig.router.constantRoutes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons;
    },
    SET_PAGES: (state, pages) => {
      /* javascript-obfuscator:disable */
      uni.setStorageSync(
        `${gVariable.StoragePrefix}pages`,
        JSON.stringify(pages)
      );
      /* javascript-obfuscator:enable */
      state.pages = pages;
    },
    SET_REALPAGEURL: (state, mapKeyToRealPageUrl) => {
      state.mapKeyToRealPageUrl = mapKeyToRealPageUrl;
    },
    SET_NAVBREADCRUMBTITLE: (state, mapKeyToNavBreadcrumbTitle) => {
      state.mapKeyToNavBreadcrumbTitle = mapKeyToNavBreadcrumbTitle;
    },
    SET_NAVTREEDATA: (state, navTreeData) => {
      /* javascript-obfuscator:disable */
      uni.setStorageSync(
        `${gVariable.StoragePrefix}navTreeData`,
        JSON.stringify(navTreeData)
      );
      /* javascript-obfuscator:enable */
      state.navTreeData = navTreeData;
    },
    SET_CURPAGEINFO: (state, curPageInfo) => {
      /* javascript-obfuscator:disable */
      uni.setStorageSync(
        `${gVariable.StoragePrefix}curPageInfo`,
        JSON.stringify(curPageInfo)
      );
      /* javascript-obfuscator:enable */
      state.curPageInfo = curPageInfo;
    },
    SET_RESOURCETYPEOPTIONS: (state, resourceTypeOptions) => {
      /* javascript-obfuscator:disable */
      uni.setStorageSync(
        `${gVariable.StoragePrefix}resourceTypeOptions`,
        JSON.stringify(resourceTypeOptions)
      );
      /* javascript-obfuscator:enable */
      state.resourceTypeOptions = resourceTypeOptions;
    },
  };
};
const mutations = getMutations(gVariable);

export const getActions = (gVariable) => {
  return {
    generateRoutes({ commit }, res) {
      return new Promise((resolve) => {
        const routeDataTree = getBackendDataItems(res).filter(
          (el) => !el[pidKeyAlias]
        );
        //console.log(res, routeDataTree, mapKeyToView, '=============aaaaa',globalConfig.router.constantResources)
        const accessedRoutes = filterAsyncRoutes({
          resources: [
            ...routeDataTree,
            ...globalConfig.router.constantResources,
          ],
        });
        accessedRoutes.push(otherResource); // 其他路由过滤
        //立刻提交页面的url映射
        commit("SET_REALPAGEURL", gVariable.mapKeyToRealPageUrl);
        commit("SET_NAVBREADCRUMBTITLE", gVariable.mapKeyToNavBreadcrumbTitle);

        const resourceData = getResourceData(routeDataTree); //获取所有按钮、页面的资源
        const buttonPermissions = resourceData.btnRes;
        const pageResources = resourceData.pageRes;
        buttonPermissions.forEach((btn) => {
          const targetJumpCode = getJumpTargetReourcePermsKey({
            [uiOptionsKeyAlias]: btn[uiOptionsKeyAlias],
          });
          let realPageKey = "";
          if (targetJumpCode) {
            const targetJumpPage = pageResources.find(
              (page) => page.code === targetJumpCode
            );
            realPageKey = targetJumpPage.realPageKey;
          } else {
            realPageKey = getRealPageFileKey(
              btn.realPageFileKey,
              btn.code,
              "Button",
              btn.depth
            );
          }
          if (realPageKey) {
            btn.targetResourceUrl = gVariable.mapKeyToRealPageUrl[realPageKey];
          }
        });

        //页面资源中加入对应页面的按钮资源 // 根据页面的Code 等于 按钮的Code的前缀 进行匹配
        pageResources.forEach((curPage) => {
          const curPageBtns = buttonPermissions.filter((btn) =>
            btn.code.startsWith(`${curPage.code}.`)
          );
          curPage.btns = curPageBtns;
        });
        // buttonPermissions = buttonPermissions.filter((item, index) => buttonPermissions.indexOf(item) === index)
        //console.log('临时看看按钮===', mapKeyToNavBreadcrumbTitle, buttonPermissions, pageResources, accessedRoutes, mapKeyToRealPageUrl)

        commit("SET_ROUTES", accessedRoutes);
        commit("SET_BUTTONS", buttonPermissions);
        commit("SET_PAGES", pageResources);
        commit("SET_NAVTREEDATA", routeDataTree);
        resolve(accessedRoutes);
      });
    },
    resetPermissions({ commit }) {
      commit("SET_ROUTES", []);
      commit("SET_BUTTONS", []);
    },
    setResourceTypeOptions: async ({ commit }, data) => {
      const resourceTypeOptions = getters.allStaticSelect["eResourceType"];
      commit("SET_RESOURCETYPEOPTIONS", resourceTypeOptions);
    },
  };
};
const actions = getActions(gVariable);
const defaultIconName = "el-icon-tools";
function filterAsyncRoutes({
  resources,
  depth: depth = 0,
  lastModulePath: lastModulePath = "",
  lastModuleTitle: lastModuleTitle = "",
  parentResource: parentResource = null,
  secondLevelRoutes: secondLevelRoutes = [],
}) {
  const res = [];
  resources.forEach((resource) => {
    callbackSetMapKeyToView(resource, depth);
    console.log(resource,'---info11')
    const curPageVmCode = generatePartialRealPageFileKeyStrategy(
      resource[resourcePermsKeyAlias]
    ); //(typeof resource[resourcePermsKeyAlias] === 'string') && resource[resourcePermsKeyAlias].split(resourcePermsKeyDefinedRule.splitStr).pop();
    let modulePath;
    //vue-router的写法: 第一级path需要/,后面层级的path不需要/,总路由是层级拼接
    if (depth === 0) {
      if (
        resource[resourceUrlKeyAlias] &&
        typeof resource[resourceUrlKeyAlias] === "string" &&
        resource[resourceUrlKeyAlias]
      ) {
        modulePath = resource[resourceUrlKeyAlias].startsWith("/")
          ? resource[resourceUrlKeyAlias]
          : `/${resource[resourceUrlKeyAlias]}`;
      } else {
        modulePath = `/${curPageVmCode}`; //`/${transName(curPageVmCode, "Pascal", "Kebab").replace(/\//g, '-')}`;
      }
    } else {
      if (
        resource[resourceUrlKeyAlias] &&
        typeof resource[resourceUrlKeyAlias] === "string" &&
        resource[resourceUrlKeyAlias]
      ) {
        modulePath = resource[resourceUrlKeyAlias].startsWith("/")
          ? resource[resourceUrlKeyAlias].substring(1)
          : `${resource[resourceUrlKeyAlias]}`;
      } else {
        modulePath = `${curPageVmCode}`; //`${transName(curPageVmCode, "Pascal", "Kebab").replace(/\//g, '-')}`;
      }
    }
    let moduleTitle = resource.meta?.title ?? resource.name;

    const jumpSuffixStr = depth === 2 ? hackSuffixJumpStr : "";
    const appendAttrObj = {};
    if (resource[resourceTypeKeyAlias] === "Menu") {
      appendAttrObj.alwaysShow = true;
    } else if (resource[resourceTypeKeyAlias] === "Page") {
      appendAttrObj.name = curPageVmCode + jumpSuffixStr;
    } else if (resource[resourceTypeKeyAlias] === "Button") {
      const permsKeyInfo = getResourcePermsKeyInfo(
        resource[resourcePermsKeyAlias]
      );
      const allVmCode = permsKeyInfo.partialKeys;
      const curVmCode = allVmCode.pop();
      const lastVmCode = allVmCode.pop();
      appendAttrObj.name = `${lastVmCode}-${curVmCode}`;
    }

    // 写了页面的key 和 没写页面的key
    let curRealPageFileKey = getRealPageFileKey(
      resource[realPageFileKeyAlias],
      resource[resourcePermsKeyAlias],
      resource[resourceTypeKeyAlias],
      depth
    );
    const getIndividualPageRule = judgeIndividualPageRule(resource, depth);
    //按钮级页面
    const isButtonLevelPage =
      resource[resourceTypeKeyAlias] === "Button" &&
      getJumpTargetVal(resource).startsWith("_") &&
      !getJumpTargetReourcePermsKey(resource);
    //按钮级跳转
    const isButtonLevelJump =
      resource[resourceTypeKeyAlias] === "Button" &&
      getJumpTargetVal(resource).startsWith("_") &&
      getJumpTargetReourcePermsKey(resource);
    //菜单级页面
    const isMenuLevelPage =
      resource[resourceTypeKeyAlias] === "Menu" &&
      getJumpTargetVal(resource).startsWith("_");
    //非一级节点的页面
    const isPageNotFirstDepth =
      resource[resourceTypeKeyAlias] === "Page" && depth > 0;
    if (resource[resourceTypeKeyAlias] === "Page" && depth === 0) {
      gVariable.mapKeyToRealPageUrl[curRealPageFileKey] = !resource[
        resourceUrlKeyAlias
      ]
        ? getCompleteUrl({
            urlInMapKeyToRealPageUrl: modulePath,
            hasPrefixSlash: true,
            realPageKey: curRealPageFileKey,
          })
        : modulePath;
    } else if (isPageNotFirstDepth || isButtonLevelPage || isMenuLevelPage) {
      gVariable.mapKeyToRealPageUrl[curRealPageFileKey] = !resource[
        resourceUrlKeyAlias
      ]
        ? getCompleteUrl({
            urlInMapKeyToRealPageUrl: `${lastModulePath}${modulePath}`,
            hasPrefixSlash: true,
            realPageKey: curRealPageFileKey,
          })
        : `${lastModulePath}${modulePath}`;
    }
    gVariable.mapKeyToNavBreadcrumbTitle[curRealPageFileKey] =
      `${lastModuleTitle}/${moduleTitle}`.startsWith("/")
        ? `${lastModuleTitle}/${moduleTitle}`.substring(1)
        : `${lastModuleTitle}/${moduleTitle}`;
    /**
     * 多层级布局，支持三级菜单
     * 页面为一级目录的情况有 childComponent
     * */
    function getMultiLevelLayout(resource) {
      function getComponent(resource, isJumpToComponent = true) {
        if (
          isJumpToComponent &&
          depth === 2 &&
          resource[resourceTypeKeyAlias] === "Page"
        ) {
          return () => Promise.resolve(); //() => import(/* @vite-ignore */`@/views/default-page/jumpto-page-index.vue`)
        } else if (
          resource[resourceTypeKeyAlias] === "Menu" &&
          !resource[pidKeyAlias]
        ) {
          return;
        } else if (
          resource[resourceTypeKeyAlias] === "Menu" &&
          resource[pidKeyAlias]
        ) {
          return middleLayout;
        } else if (resource[realPageFileKeyAlias]) {
          return mapKeyToView[resource[realPageFileKeyAlias]].view;
        } else if (getIndividualPageRule.isMatch) {
          return mapKeyToView[getIndividualPageRule.realPageFilePathKey].view;
        } else if (resource[resourceTypeKeyAlias] === "Button") {
          if (getJumpTargetVal(resource) === "_tab") {
            return () => Promise.resolve; //() => import(/* @vite-ignore */`@/views/default-page/new-tab-page.vue`)
          } else {
            return () => Promise.resolve; //() => import(/* @vite-ignore */`@/views/default-page/new-target-page.vue`)
          }
        } else {
          return () => Promise.resolve; //() => import(/* @vite-ignore */`@/views/default-page/curd-page-index.vue`)
        }
      }
      const component = getComponent(resource);
      const jumpToComponent = getComponent(resource, false);
      if (
        (resource[resourceTypeKeyAlias] === "Page" && !resource[pidKeyAlias]) ||
        (resource[resourceTypeKeyAlias] === "Button" &&
          getJumpTargetVal(resource).startsWith("_"))
      ) {
        return {
          curComponent: Layout,
          childComponent: component,
          jumpToComponent: null,
        };
      } else {
        return {
          curComponent: component,
          childComponent: null,
          jumpToComponent: jumpToComponent,
        };
      }
    }
    const multiLevelLayout = getMultiLevelLayout(resource);
    //const curPageVmCode = (typeof resource[resourcePermsKeyAlias] === 'string') && resource[resourcePermsKeyAlias].split(resourcePermsKeyDefinedRule.splitStr).pop()

    const tmp = {
      path: multiLevelLayout.childComponent ? "/" : modulePath + jumpSuffixStr,
      //name: curPageVmCode,//resource[resourceUrlKeyAlias] || resource[idKeyAlias],
      // iconUrl: resource.menuIcon,
      meta: {
        title: resource[resourceNameAlias],
        icon: resource[resourceIconAlias] || defaultIconName,
        resourcePerms: resource[resourcePermsKeyAlias],
        noCache: jumpSuffixStr ? true : false,
        hiddenTag: jumpSuffixStr ? true : false,
      },
      component: multiLevelLayout.curComponent,
      hidden:
        !resource["isShow"] ||
        ["Button", "Interface"].includes(resource[resourceTypeKeyAlias]),
      ...appendAttrObj,
    };
    //页面为一级目录的情况
    if (multiLevelLayout.childComponent) {
      const isNewPage = getJumpTargetVal(resource) === "_blank";
      if (!isNewPage && resource[resourceTypeKeyAlias] === "Menu") {
        tmp["children"] = [
          {
            path: modulePath,
            //name: curPageVmCode,//resource[resourceUrlKeyAlias] || resource[idKeyAlias],
            // iconUrl: resource.menuIcon,
            meta: {
              title: resource[resourceNameAlias],
              icon: resource[resourceIconAlias] || defaultIconName,
              resourcePerms: resource[resourcePermsKeyAlias],
            },
            component: multiLevelLayout.childComponent,
            hidden:
              !resource["isShow"] ||
              ["Button", "Interface"].includes(resource[resourceTypeKeyAlias]),
            ...appendAttrObj,
          },
        ];
      } else {
        const isnewTab =
          resource[resourceTypeKeyAlias] === "Button" &&
          getJumpTargetVal(resource) === "_tab";
        tmp.path = isnewTab ? lastModulePath + modulePath : modulePath;
        tmp.component = multiLevelLayout.childComponent;
      }
    }
    const hasChildRouter =
      (resource[childrenKeyAlias] &&
        resource[resourceTypeKeyAlias] === "Menu") ||
      (resource[resourceTypeKeyAlias] === "Page" &&
        resource[childrenKeyAlias].some((el) =>
          getJumpTargetVal(el).startsWith("_")
        ));
    if (hasChildRouter) {
      //
      tmp["children"] = filterAsyncRoutes({
        resources: resource[childrenKeyAlias],
        depth: depth + 1,
        lastModulePath: lastModulePath + modulePath + "/",
        lastModuleTitle: lastModuleTitle + "/" + moduleTitle,
        parentResource: resource,
        secondLevelRoutes: depth <= 0 ? [] : secondLevelRoutes,
      });
    }
    let tmpBtns = [];
    //当前资源类型是页面,并且子资源(按钮)有跳转新页面的动作,则此种按钮也得加到 mapKeyToRealPageUrl 中
    if (
      resource[resourceTypeKeyAlias] === "Page" &&
      resource[childrenKeyAlias].some((el) =>
        getJumpTargetVal(el).startsWith("_")
      )
    ) {
      tmpBtns = filterAsyncRoutes({
        resources: resource[childrenKeyAlias],
        depth: depth + 2,
        lastModulePath: lastModulePath + modulePath + "/",
        lastModuleTitle: lastModuleTitle + "/" + moduleTitle,
        parentResource: resource,
        secondLevelRoutes: depth <= 0 ? [] : secondLevelRoutes,
      });
    }
    //按钮级页面
    //const isButtonLevelPage = resource[resourceTypeKeyAlias] === "Button" && getJumpTargetVal(resource).startsWith("_") && !getJumpTargetReourcePermsKey(resource);
    const isInRouter =
      ["Menu", "Page"].includes(resource[resourceTypeKeyAlias]) ||
      resource[realPageFileKeyAlias] ||
      isButtonLevelPage;
    // 只添加菜单
    if (isInRouter) {
      //  || (resource[resourceTypeKeyAlias] === "Page" && resource[childrenKeyAlias].some(el => getJumpTargetVal(el).startsWith("_")))

      res.push(tmp, ...tmpBtns);
    }
    const isInSecondRouter =
      (resource[resourceTypeKeyAlias] === "Page" && depth >= 2) ||
      isButtonLevelPage;
    //如果是三级页面,需要加到二级里面
    if (isInSecondRouter) {
      let jumpToTmp = {};
      if (isButtonLevelPage) {
        jumpToTmp = {
          path: `${lastModulePath}${modulePath}`,
          //name: curPageVmCode,//resource[resourceUrlKeyAlias] || resource[idKeyAlias],
          // iconUrl: resource.menuIcon,
          meta: {
            title: resource[resourceNameAlias],
            icon: resource[resourceIconAlias] || defaultIconName,
            resourcePerms: resource[resourcePermsKeyAlias],
          },
          component: () => Promise.resolve, //() => import(/* @vite-ignore */`@/views/default-page/new-tab-page.vue`),
          hidden: true,
          ...appendAttrObj,
          //name: appendAttrObj.name.replace("_Btn", '')
        };
      } else {
        jumpToTmp = {
          path: multiLevelLayout.childComponent
            ? "/"
            : `${lastModulePath}${modulePath}`,
          //name: curPageVmCode,//resource[resourceUrlKeyAlias] || resource[idKeyAlias],
          // iconUrl: resource.menuIcon,
          meta: {
            title: resource[resourceNameAlias],
            icon: resource[resourceIconAlias] || defaultIconName,
            resourcePerms: resource[resourcePermsKeyAlias],
          },
          component: () => Promise.resolve, //() => import(/* @vite-ignore */`@/views/default-page/curd-page-index.vue`),
          hidden: true,
          ...appendAttrObj,
          name: appendAttrObj.name.replace(hackSuffixJumpStr, ""),
        };
      }
      if (secondLevelRoutes.every((el) => el.path !== jumpToTmp.path)) {
        secondLevelRoutes.push(jumpToTmp);
      }
    }
    /* if (resource[childrenKeyAlias] && resource[resourceTypeKeyAlias] === "Page") {
          res = res.concat(filterAsyncRoutes(resource[childrenKeyAlias].filter(item => item[resourceUrlKeyAlias] != null), depth + 1, mapKeyToRealPageUrl[curRealPageFileKey], resource))
        } */
  });
  return res;
}
/**
 * 单个页面资源数据
 */
const getResourcePageData = (resource, depth) => {
  const curRealPageFileKey = getRealPageFileKey(
    resource[realPageFileKeyAlias],
    resource[resourcePermsKeyAlias],
    resource[resourceTypeKeyAlias],
    depth
  );
  const uiOptions = resource?.[uiOptionsKeyAlias]
    ? resource[uiOptionsKeyAlias]
    : {};
  const permsKeyInfo = getResourcePermsKeyInfo(resource[resourcePermsKeyAlias]);
  const [lastOnePermCode = "", beforeLastOnePermCode = ""] =
    permsKeyInfo.partialKeys.reverse();
  //console.log(uiOptions,'字段')
  const curPageVmCode = getCurResourceLastCode(resource);
  const pageData = {
    [uiOptionsKeyAlias]: uiOptions, //页面的扩展字段
    name: resource[resourceNameAlias], //页面在导航菜单中的名字
    code: resource[resourcePermsKeyAlias], //页面完整的Code
    vmCode:
      resource[resourceTypeKeyAlias] === "Button"
        ? `${beforeLastOnePermCode}${permsKeyInfo.splitStr}${lastOnePermCode}`
        : curPageVmCode, //页面对应的VmCode
    depth, //层级深度
    targetResourceUrl: gVariable.mapKeyToRealPageUrl[curRealPageFileKey],
    resource,
    resourceType: resource[resourceTypeKeyAlias],
    realPageKey: curRealPageFileKey, //用于 页面个性化定制时的文件路径;也用于跳转到指定页面Url的key,用这个key在mapKeyToRealPageUrl中找到url
  };
  return pageData;
};
/**
 * 单个按钮资源数据
 */
const getResourceBtnData = (resource, depth) => {
  const curRealPageFileKey = getRealPageFileKey(
    resource[realPageFileKeyAlias],
    resource[resourcePermsKeyAlias],
    resource[resourceTypeKeyAlias],
    depth
  );
  const uiOptions = resource?.[uiOptionsKeyAlias]
    ? resource[uiOptionsKeyAlias]
    : {};
  ////////////////
  const permsKeyInfo = getResourcePermsKeyInfo(resource[resourcePermsKeyAlias]);
  const [lastOnePermCode = "", beforeLastOnePermCode = ""] =
    permsKeyInfo.partialKeys.reverse();
  const curBtnMetaKeyInfix = transName(lastOnePermCode, "Pascal", "Kebab"); //按钮key的中缀
  let curBtnMetaKey =
    (uiOptions?.btnSiteInfo ?? "table") === "table"
      ? `table-${curBtnMetaKeyInfix}-btn`
      : `form-${curBtnMetaKeyInfix}-above-table`;
  /* if((uiOptions?.btnSiteInfo ?? "table") === 'table'){
    } */
  let curBtnEventStrategyName = `${
    (uiOptions?.btnSiteInfo ?? "table") === "table"
      ? uiOptions?.isTableBatch ?? false
        ? "TableBatch"
        : "TableSingle"
      : "Form"
  }${lastOnePermCode}${uiOptions?.btnEventStrategyInfo ?? "DialogFormOpen"}`;
  const matchedBuildInBtnInfoKey = allBuildInBtnInfoKeys.find((btnInfoKey) =>
    resource[resourcePermsKeyAlias].endsWith(
      resourcePermsKeyDefinedRule.buildInBtnInfo[btnInfoKey].CodeSuffix
    )
  );
  if (matchedBuildInBtnInfoKey) {
    curBtnMetaKey =
      resourcePermsKeyDefinedRule.buildInBtnInfo[matchedBuildInBtnInfoKey]
        .MetaKey;
  }
  ///////////////
  let targetResourceUrl = ""; //先把目标资源url都设置成'',后面等pageRes都填充完后,在把btnRes里 根据 uiOptions 里的跳转信息,补充完整 targetResourceUrl
  const btnData = {
    code: resource[resourcePermsKeyAlias], //按钮的完整Code
    name: resource[resourceNameAlias], //按钮的名字
    targetResourceUrl, // 按钮会跳转的url,如按钮为不跳转按钮,则为 ""
    realPageFileKey: curRealPageFileKey, //按钮的url访问的key
    depth,
    target: getJumpTargetVal(resource), //按钮的跳转方式,有些不是弹窗表单形式,是新页面表单形式
    vmCode: `${beforeLastOnePermCode}${permsKeyInfo.splitStr}${lastOnePermCode}`,
    [uiOptionsKeyAlias]: uiOptions, //按钮的扩展字段
    metaKey: curBtnMetaKey, //按钮在组件元数据中使用的key
    eventStrategyName: curBtnEventStrategyName, //按钮在组件元数据中使用的触发事件名称
  };
  return btnData;
};
export function getResourceData(resources, depth = 0) {
  let btnRes = [];
  let pageRes = [];
  resources.forEach((resource) => {
    //不是按钮的需要递归的情况
    if (
      resource[childrenKeyAlias] &&
      ["Menu", "Page"].includes(resource[resourceTypeKeyAlias])
    ) {
      btnRes = btnRes.concat(
        getResourceData(resource[childrenKeyAlias], depth + 1).btnRes
      );

      //保存页面的数据, 包括 page-style
      if (resource[childrenKeyAlias]) {
        //  && resource[resourceTypeKeyAlias] === "Menu"
        pageRes = pageRes.concat(
          getResourceData(resource[childrenKeyAlias], depth + 1).pageRes
        );
      }
      const isPlainPage = resource[resourceTypeKeyAlias] === "Page";
      const isMenuLevelPage =
        resource[resourceTypeKeyAlias] === "Menu" &&
        getJumpTargetVal(resource).startsWith("_");
      if (isPlainPage || isMenuLevelPage) {
        const pageData = getResourcePageData(resource, depth);
        pageRes = pageRes.concat(pageData);
      }
    }
    //是按钮结束递归情况
    else if (
      resource[resourceTypeKeyAlias] === "Button" &&
      resource[resourcePermsKeyAlias]
    ) {
      const btnData = getResourceBtnData(resource, depth);
      btnRes = btnRes.concat(btnData);

      const isButtonLevelPage =
        getJumpTargetVal(resource).startsWith("_") &&
        !getJumpTargetReourcePermsKey(resource);
      if (isButtonLevelPage) {
        const pageData = getResourcePageData(resource, depth);
        pageRes = pageRes.concat(pageData);
      }
    }
  });
  return { btnRes, pageRes };
}

const otherResource = {
  path: "*",
  redirect: "/404",
  hidden: true,
};

/**
 * 当调用filterAsyncRoutes时,会顺带把 mapKeyToView 值填充完成
 */
function callbackSetMapKeyToView(node, depth) {
  const getIndividualPageRule = judgeIndividualPageRule(node, depth);
  if (node[realPageFileKeyAlias] && !getIndividualPageRule.isMatch) {
    const realPageFilePath = node[realPageFileKeyAlias]; //变量提升;防止 Promise.resolve 异步中 的 变量出错
    mapKeyToView[node[realPageFileKeyAlias]] = {
      [realPageFileKeyAlias]: realPageFilePath,
      view: () =>
        Promise.resolve(require(`@/views/${realPageFilePath}/index.vue`)),
    };
  } else if (getIndividualPageRule.isMatch) {
    mapKeyToView[getIndividualPageRule.realPageFilePathKey] = {
      [realPageFileKeyAlias]: getIndividualPageRule.realPageFilePathKey,
      view: () =>
        Promise.resolve(
          require(`@/views/${getIndividualPageRule.realPageFilePathKey}/index.vue`)
        ),
    };
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
